const { getUserTaskCheckInPageListForDate } = require('../../../utils/task');
const { formatDateTime, formatDateTimeNoSeconds } = require('../../../utils/date');

Page({
  data: {
    tabList: [
      {
        label: '未打卡',
        value: 'wait_check_in'
      },
      {
        label: '已完成',
        value: 'finish'
      },
      {
        label: '已过期',
        value: 'overdue'  
      },
      {
        label: '已退出',
        value: 'quit'
      }
    ],
    date: '', // 当前选择日期
    maxDate: '', // 日历最大可选日期
    activeTab: 0, // 当前tab
    taskList: [[], [], [], []], // 四个tab的数据，顺序与tabList一致
    loading: false,
    hasMore: true,
    page: [1, 1, 1, 1], // 各tab分页
    size: 10
  },
  
  // 用于取消请求的标识
  currentRequestId: 0,
  
  onLoad() {
    const today = this.formatDate(new Date());
    const maxDate = this.formatDate(new Date(Date.now() + 24 * 60 * 60 * 1000));
    this.setData({ date: today, maxDate });
    this.loadTasks(true);
  },
  
  formatDate(date) {
    const y = date.getFullYear();
    const m = (date.getMonth() + 1).toString().padStart(2, '0');
    const d = date.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${d}`;
  },
  
  onDateChange(e) {
    this.setData({ 
      date: e.detail.value, 
      activeTab: 0, 
      taskList: [[], [], [], []], 
      page: [1, 1, 1, 1], 
      hasMore: true 
    }, () => {
      this.loadTasks(true);
    });
  },
  
  onTabChange(e) {
    const idx = Number(e.currentTarget.dataset.index);
    if (this.data.activeTab === idx) return;
    
    // 取消当前正在进行的请求
    this.currentRequestId++;
    
    this.setData({ activeTab: idx }, () => {
      // 每次切换tab都重新加载数据
      this.loadTasks(true);
    });
  },
  
  onScrollToLower() {
    this.loadTasks(false);
  },
  
  async loadTasks(reset) {
    if (this.data.loading || (!this.data.hasMore && !reset)) return;
    
    // 生成新的请求ID
    const requestId = ++this.currentRequestId;
    
    this.setData({ loading: true });
    const current = reset ? 1 : this.data.page[this.data.activeTab];
    const size = this.data.size;
    const state = this.data.tabList[this.data.activeTab].value;
    
    try {
      const res = await getUserTaskCheckInPageListForDate(
        this.data.date,
        state,
        current,
        size
      );

      // 检查请求是否已被取消
      if (requestId !== this.currentRequestId) {
        console.log('请求已被取消，忽略响应');
        return;
      }

      const newTasks = res.records || [];
      const tasks = reset ? newTasks : (this.data.taskList[this.data.activeTab] || []).concat(newTasks);
      // 格式化时间
      tasks.forEach(task => {
        task.taskStartTime = formatDateTime(task.taskStartTime);
        task.taskEndTime = formatDateTime(task.taskEndTime);
        task.checkInTimeFmt = formatDateTimeNoSeconds(task.checkInTime);
      });

      // 更新对应tab的数据
      const taskList = Array.isArray(this.data.taskList) && this.data.taskList.length === 4 ? this.data.taskList.slice() : [[], [], [], []];
      taskList[this.data.activeTab] = tasks;
      const pageArr = Array.isArray(this.data.page) && this.data.page.length === 4 ? this.data.page.slice() : [1, 1, 1, 1];
      pageArr[this.data.activeTab] = current + 1;
      this.setData({
        taskList,
        loading: false,
        hasMore: tasks.length < (res.total || 0),
        page: pageArr
      });
    } catch (e) {
      // 检查请求是否已被取消
      if (requestId !== this.currentRequestId) {
        console.log('请求已被取消，忽略错误');
        return;
      }
      
      this.setData({ loading: false });
      wx.showToast({ title: '加载任务失败', icon: 'none' });
    }
  },
  
  onTaskTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/task/task-detail/task-detail?id=${id}` });
  },
  
  onCheckInDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/task/check-in-detail/check-in-detail?id=${id}` });
  }
}); 